package com.hy.storage.service.impl;

import com.hy.storage.mapper.StorageMapper;
import com.hy.storage.service.StorageService;
import com.hy.storage.service.StorageServiceXA;
import com.hy.storage.service.StorageTccAction;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

@Slf4j
@Service
public class StorageServiceImpl implements StorageService {

    @Resource
    StorageMapper storageMapper;
    @Autowired
    StorageTccAction storageTccAction;
    @Autowired
    StorageServiceXA storageServiceXA;

    /**
     * AT 模式
     * @param productId
     * @param currentUsed
     * @return
     */
    @Override
    public String updateUsed(long productId, long currentUsed) {
        return storageMapper.updateUsed(productId,currentUsed)+"成功！";
    }

    /**
     * TTC 模式
     * @param productId
     * @param quantity
     * @return
     */
    @Override
    //@GlobalTransactional
    @Transactional
    public boolean reduceStock(long productId, long quantity) {
        boolean res = storageTccAction.reduceStock(null,productId, quantity);
        // 出错测试
        //int i = 1/0;
        if (!res){
            throw new RuntimeException("减库存出错！");
        }
        return res;
    }

    @Override
    public boolean reduceStockByXA(long productId, long quantity) {
        boolean res = storageServiceXA.reduceStockByXA(productId, quantity);
        if (!res){
            throw new RuntimeException("减库存出错！");
        }
        return res;
    }
}
